package com.mjoys.common.serializer;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

public class CustomDateDeserializer extends JsonDeserializer<Date> {

    @Override
    public Date deserialize(JsonParser parser, DeserializationContext context)
            throws IOException, JsonProcessingException {
        try {
            if(parser.getValueAsString()!=null){
                Date date = null;
                if(date==null){
                    date = this.dateFormat(parser.getValueAsString(), "yyyy-MM-dd HH:mm:ss");
                }
                if(date==null){
                    date = this.dateFormat(parser.getValueAsString(), "yyyy-MM-dd");
                }
                return date;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private Date dateFormat(String str,String pattern){
        try {
            if(str!=null){
                SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                return sdf.parse(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}